package com.d5xx.hunters.events;

import com.d5xx.hunters.API.Hunter;
import com.d5xx.hunters.API.HunterGame;
import com.d5xx.hunters.API.HunterPlayer;
import org.bukkit.Bukkit;
import org.bukkit.Sound;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageEvent;

import static com.d5xx.hunters.Variables.plugin;


public class GameDeath implements Listener {
    @EventHandler
    public void OnPlayerDeath(EntityDamageEvent event) {
        if (!(event.getEntity() instanceof Player bukkitPlayer)) return;

        HunterPlayer hunterPlayer = Hunter.getHunterPlayer(bukkitPlayer);

        if (hunterPlayer.getType().equals("game")) { // 判断模式
            if (hunterPlayer.getPlayer().getHealth() <= event.getDamage()) { // 死亡条件
                event.setCancelled(true); //终止事件

                hunterPlayer.setType("death");

                Hunter.dropPlayerItems(bukkitPlayer); // 把玩家的物品留下

                HunterGame game = Hunter.getGame(bukkitPlayer.getWorld()); // 获取hunterGame实例

                Bukkit.getScheduler().runTask(plugin, () ->
                        game.getWorld().playSound(bukkitPlayer.getLocation(), Sound.ENTITY_PLAYER_DEATH, 1, 1)); // 玩家死亡声音

                PlayerDeath(hunterPlayer, bukkitPlayer, game);
            }
        }
    }

    private void PlayerDeath(HunterPlayer player, Player bukkitPlayer, HunterGame game) {
        if (game.getPlayerMode(player).equals("hunter")) { // 当死亡的是猎人时

            if (bukkitPlayer.getBedSpawnLocation() != null) { // 判断是否有设置过出生点
                bukkitPlayer.teleport(bukkitPlayer.getBedSpawnLocation());
            } else {
                bukkitPlayer.teleport(game.getWorld().getSpawnLocation());
            }
            bukkitPlayer.setHealth(20); //复活
            bukkitPlayer.sendTitle(player.getKeyMessage("game-respawn-title"), "", 5, 20, 5);
            player.setType("game");

        } else {
            game.endByHunter(player);
        }
    }

}
